import { useState, useEffect } from 'react'
import './App.css'
import { getDate, delFn, addFn, changeFn } from "./uite"
function App() {
  const [list, setList] = useState([])
  const getAll = () => {
    const res = getDate().then((a) => {
      setList(a.data)
    })
  }
  useEffect(() => {
    getAll()
  }, [])
  async function Del(id) {
    await delFn(id)
    getAll()
  }
  async function add(obj) {
    await addFn(obj)
    getAll()
  }
  async function change(id, type) {
    let index = list.findIndex(i => i.id == id)
    if (type) {
      let a = list[index].num + 1
      let obj = {
        num: a
      }
      await changeFn(id, obj)
      getAll()
    } else {
      if (list[index].num > 0) {
        let a = list[index].num - 1
        let obj = {
          num: a
        }
        await changeFn(id, obj)
        getAll()
      }
    }
  }
  return (
    <div>
      {
        list.map(item => {
          return (
            <div key={item.id}
              style={{ display: "flex", width: "50vw", justifyContent: "space-evenly" }}
            >
              <p>  <b>商品名称:</b>{item.name}</p>
              <p><b>  数量:</b><button onClick={() => change(item.id, false)}>-</button>{item.num}<button onClick={() => change(item.id, true)}>+</button></p>
              <p> <b> 价格:</b>{item.price}</p>
              <div>
                <button onClick={() => Del(item.id)}>删除</button>
              </div>
            </div>
          )
        })
      }
      <button onClick={() => add({ id: list.length, num: "1", name: "鼠标", price: "200" })}>添加</button>
    </div>
  )
}

export default App
